package com.lsh.oms.core.dao.mybatis.handler;

import org.apache.ibatis.jdbc.RuntimeSqlException;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.*;
import java.util.Calendar;
import java.util.TimeZone;

public class InstantTypeHandler implements TypeHandler<Object> {

    private static final Calendar UTC_CALENDAR = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    @Override
    public void setParameter(PreparedStatement ps, int i, Object obj, JdbcType jdbcType) throws SQLException {
        String timestamp = obj.toString();
        long mills = Long.parseLong(obj.toString());
        mills = (timestamp.length() == 10) ? mills * 1000L : mills;
        ps.setTimestamp(i, new Timestamp(mills), UTC_CALENDAR);
    }

    @Override
    public Long getResult(ResultSet rs, String columnName) throws SQLException {
        throw new RuntimeSqlException("instant cannot get by getResult(ResultSet rs, String columnName)");
    }

    @Override
    public Long getResult(ResultSet rs, int columnIndex) throws SQLException {
        throw new RuntimeSqlException("instant cannot get by getResult(ResultSet rs, int columnIndex)");
    }

    @Override
    public Long getResult(CallableStatement cs, int columnIndex) throws SQLException {
        throw new RuntimeSqlException("instant cannot get by getResult(CallableStatement cs, int columnIndex)");
    }
}
